package cz.muni.fi.pa165.dundd.daoimpl;

import cz.muni.fi.pa165.dundd.entity.Hero;
import cz.muni.fi.pa165.dundd.dao.HeroDAO;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;

/**
 *
 * @author xszanto1 <ardos@mail.muni.cz>, xdemocko
 */
@Repository
public class HeroDAOImpl implements HeroDAO {

    @PersistenceContext
    private EntityManager em;

    @Override
    public void createHero(Hero hero) {
        em.persist(hero);
    }

    @Override
    public Hero retrieveHero(Long id) {
        return em.find(Hero.class, id);
    }

    @Override
    public List<Hero> retrieveAllHeroes() {
        return em.createQuery("SELECT p from Hero p").getResultList();
    }

    @Override
    public void updateHero(Hero hero) {
        em.merge(hero);
    }

    @Override
    public void deleteHero(Hero hero) {
        em.remove(em.contains(hero) ? hero : em.merge(hero));
    }

    @Override
    public Hero retrieveHero(String name) {
        if (name == null || name.equals("")) {
            throw new IllegalArgumentException("name must not be empty/null");
        }
        Hero hero = (Hero) em.createQuery("SELECT h FROM Hero h WHERE h.name = :name").setParameter("name", name).getSingleResult();
        return hero;
    }

}
